package cn.rwklyd.BookKeeping.handler;

import cn.rwklyd.BookKeeping.constant.MessageConstant;
import cn.rwklyd.BookKeeping.pojo.Result;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

// 匿名用户访问无权限资源时的处理器
// 用于未提供 JWT或无效或过期的 JWT 的场景(有JWT不需要实现)
@Component
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 设置客户端响应编码格式
        response.setContentType("application/json;charset=utf-8");
        String result = null;
        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        if (authException instanceof InternalAuthenticationServiceException){  // 用户名不存在
            result = JSON.toJSONString(Result.error(MessageConstant.ACCOUNT_NOT_FOUND));
        } else if (authException instanceof BadCredentialsException) {                       // 密码错误
            result = JSON.toJSONString(Result.error(authException.getMessage()));
        } else{
            result = JSON.toJSONString(Result.error(MessageConstant.ANONYMOUS_NO_PERMISSION));
        }
        outputStream.write(result.getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
